package edu.jhu.secondhome.servlet;

import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.jhu.secondhome.database.beans.Reservation;

import edu.jhu.secondhome.database.accessors.ReservationAccessor;

import edu.jhu.secondhome.database.accessors.HotelAccessor;
import edu.jhu.secondhome.database.accessors.RoomAccessor;
import edu.jhu.secondhome.database.beans.Hotel;
import edu.jhu.secondhome.database.beans.Room;
import edu.jhu.secondhome.database.beans.User;

public class ReservationCreationServlet extends HttpServlet
{
  /**
   * 
   **/
  private static final long serialVersionUID = -1960544717340243343L;

  private static final long MS_PER_DAY = 86400000;

  public void init() throws ServletException
  {

  }

  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
  {
    processRequest(req, resp);
  }

  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
  {
    processRequest(req, resp);
  }

  public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    response.setContentType("text/html;charset=UTF-8");
    ServletContext servletContext = getServletContext();
    HttpSession session = request.getSession();

    ArrayList<String> errors = new ArrayList<String>();
    request.setAttribute("errors", errors);

    User user = (User) session.getAttribute( "user" );
    
    String cardNum = request.getParameter( "cardNumber" );
    String expMonth = request.getParameter( "expMonth" );
    String expYear = request.getParameter( "expYear" );
    String secCode = request.getParameter( "securityCode" );
    
    String roomNum = request.getParameter( "roomNum" );
    String hotelName = request.getParameter( "hotelName" );
    String checkin = request.getParameter( "check-in" );
    String numDays = request.getParameter( "numDays" );
    String numPeople = request.getParameter( "numPeople" );

    try
    {
      //TODO set the credit card info on the user and add to database
//      user.setCr
      
      int occupancy = Integer.parseInt( numPeople );
      int duration = Integer.parseInt( numDays );
      SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
      java.util.Date utilCheckinDate = format.parse( checkin );

      if( !( utilCheckinDate instanceof java.util.Date ) )  
      {
        errors.add( "You must provide check-in and check-out dates in the form MM/dd/yyyy." );
        RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/index.jsp");
        dispatcher.forward(request, response);
        return;
      }

      Date checkinDate = new Date( utilCheckinDate.getTime() );
      RoomAccessor roomsDb = new RoomAccessor();
      
      synchronized ( this )
      {
      boolean available = roomsDb.isRoomAvailableForDuration( hotelName, roomNum, utilCheckinDate, duration );
      System.out.println("Available is " + available);
      if ( available )
      {
        Room room = roomsDb.getRoom( hotelName, roomNum );
        ReservationAccessor reservationDb = new ReservationAccessor();
        Reservation reservation = new Reservation();
        reservation.setEmail( user.getEmail() );
        reservation.setHotelName( hotelName );
        reservation.setNumOfDays( duration );
        reservation.setNumOfPeople( occupancy );
        reservation.setRoomNumber( roomNum );
        reservation.setStartDate( utilCheckinDate );
        reservation.setTotalCost( room.getCostPerNight() * duration );
        reservationDb.insertReservation( reservation );

        request.setAttribute("message", "You have successfully reserved Room #" + roomNum +
            " at " + hotelName + " on " + format.format( utilCheckinDate ) + " for " + duration +
            " nights." );

        RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/index.jsp");
        dispatcher.forward(request, response);
        return;
      }
      else
      {
        long start = utilCheckinDate.getTime();
        long end = start + ( MS_PER_DAY * duration );
        
        String checkout = format.format( new Date( end ) );
        
        errors.add( "We're sorry, that room is no longer available.  Please try again." );
        request.setAttribute( "check-in", checkin );
        request.setAttribute( "checkout", checkout );
        request.setAttribute( "numPeople", numPeople );
        RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/reservationSearch");
        dispatcher.forward(request, response);
        return;
      }
      
//      HotelAccessor hotelsDb = new HotelAccessor();
//      
      }
//
//      long start = checkinDate.getTime();
//      long end = start + (MS_PER_DAY * duration);
//      String checkout = format.format( new Date( end ) );
//
//      request.setAttribute( "check-in", checkin );
//      request.setAttribute( "check-out", checkout );
//      request.setAttribute( "numDays", duration );
//      request.setAttribute( "numPeople", occupancy );
//
//      RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/search/hotelInfo.jsp");
//      dispatcher.forward(request, response);
//      return;
    } catch ( SQLException e1 )
    {
      // TODO Auto-generated catch block
      e1.printStackTrace();
      errors.add( e1.getMessage() );
    } catch ( ParseException pe )
    {
      errors.add( "You must supply valid check-in and check-out dates." );
    } catch ( NumberFormatException nfe )
    {
      errors.add( "You must supply a valid integer for number of people." );
    }
//
//    RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/index.jsp");
//    dispatcher.forward(request, response);
//    return;
  }
}
